package ghost;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.*;
import jxl.write.biff.RowsExceededException;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by Ghost on 2014/12/15 0015.
 */
class Bag implements Comparable {
    private String date;
    private String data;

    Bag(String date, String data) {
        this.date = date;
        this.data = data;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    public String getDate() {
        return date;
    }

    @Override
    public int compareTo(Object o) {
        Bag bag = (Bag) o;
        int year = Integer.parseInt(bag.getDate().split("-")[0]);
        int month = Integer.parseInt(bag.getDate().split("-")[1]);
        int day = Integer.parseInt(bag.getDate().split("-")[2]);

        int thisYear = Integer.parseInt(this.date.split("-")[0]);
        int thisMonth = Integer.parseInt(this.date.split("-")[1]);
        int thisDay = Integer.parseInt(this.date.split("-")[2]);

        if (year > thisYear)
            return -1;
        else if (year < thisYear) {
            return 1;
        } else {
            if (month > thisMonth)
                return -1;
            else if (month < thisMonth)
                return 1;
            else {
                if (day > thisDay)
                    return -1;
                else if (day < thisDay)
                    return 1;
                else
                    return 0;
            }
        }
    }
}

public class ActionFinanceDataProcess {
    private String firstSepDate = null;
    private String location = null;
    private int days;

    public void init(String location, String firstSepDate, int days) {
        this.location = location;
        this.firstSepDate = firstSepDate;
        this.days = days;
    }

    public List<Bag> readXLS() {
        File file = new File(this.location);
        try {
            Workbook workbook = Workbook.getWorkbook(file);
            int sheetNum = workbook.getNumberOfSheets();
            List<Bag> list = new ArrayList<Bag>();
            for (int i = 0; i < sheetNum; i++) {
                Sheet sheet = workbook.getSheet(i);
                int rows = sheet.getRows();
                int columns = sheet.getColumns();

                for (int row = 1; row < rows; row++) {
                    StringBuffer sb = new StringBuffer("");
                    String date = "";
                    for (int column = 0; column < columns; column++) {

                        Cell cell = sheet.getCell(column, row);

                        sb.append("," + cell.getContents());
                        if (column == 2) {

                            date = cell.getContents();
                        }
                    }
                    if (date != null && date.length() > 0)
                        list.add(new Bag(date, sb.toString()));
                }
            }
            workbook.close();
            String firstDate = list.get(0).getDate();
            int firstYear = Integer.parseInt(firstDate.split("-")[0]);
            int firstMonth = Integer.parseInt(firstDate.split("-")[1]);
            int firstDay = Integer.parseInt(firstDate.split("-")[2]);
            String lastDate = list.get(list.size() - 1).getDate();
            int lastYear = Integer.parseInt(lastDate.split("-")[0]);
            int lastMonth = Integer.parseInt(lastDate.split("-")[1]);
            int lastDay = Integer.parseInt(lastDate.split("-")[2]);
            String[] regex = this.firstSepDate.split("-");
            int month = Integer.parseInt(regex[1]);
            int day = Integer.parseInt(regex[2]);
            for (int i = firstYear; i <= lastYear; i++) {
                list.add(new Bag("" + i + "-" + regex[1] + "-" + regex[2], ""));
            }
            Collections.sort(list);
            return list;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (BiffException e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<Bag> search(List<Bag> allBags) {
        List<Bag> rst = new LinkedList<Bag>();
        String[] regex = this.firstSepDate.split("-");
        String match = regex[1] + "-" + regex[2];
        int len = allBags.size();
        for (int i = 0; i < len; i++) {
            String date = allBags.get(i).getDate();
            String subDate = date.split("-")[1] + "-" + date.split("-")[2];
            if (subDate.contains(match)) {
                for (int j = -1 * days; j <= days; j++) {
                    if (i + j >= 0 && i + j < len && j != 0)
                        rst.add(allBags.get(i + j));
                }
            }
        }
        return rst;
    }

    public void generateResult(List<Bag> list) {
        File file = new File(this.location);

        String fileName = getFileName(file);
        file = new File("public/Rst" + fileName);
        WritableWorkbook newbook = null;
        WritableSheet writableSheet = null;
        try {
            newbook = Workbook.createWorkbook(file);
            writableSheet = newbook.createSheet("result", 0);
            List<String> titles = new LinkedList<String>();
            titles.add("代码");
            titles.add("简称");
            titles.add("日期");
            titles.add("前收盘价");
            titles.add("开盘价");
            titles.add("最高价");
            titles.add("最低价");
            titles.add("收盘价");
            titles.add("成交量（股）");
            titles.add("成交金额（元）");
            titles.add("涨跌");
            titles.add("涨跌幅（%）");
            for (int i = 0; i < 12; i++) {
                Label label = new Label(i, 0, titles.get(i));
                writableSheet.addCell(label);
            }
            int row = 1;
            for (Bag bag : list) {

                String[] datas = bag.getData().split(",");
                for (int i = 1; i < datas.length; i++) {
                    Label label = new Label(i - 1, row, datas[i]);
                    writableSheet.addCell(label);
                }
                row++;
            }
            newbook.write();
            newbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (RowsExceededException e) {
            e.printStackTrace();
        } catch (WriteException e) {
            e.printStackTrace();
        }

    }


    public String getFileName(File file) {
        return file.getName();
    }

    public static void main(String[] args) {

        if (args != null && args.length == 2) {
            String sepDate = args[0];
            int days = Integer.parseInt(args[1]);

            File file = new File("public/");
            File[] files = file.listFiles();
            for (File subFile : files) {
                String fileName = subFile.getName();
                ActionFinanceDataProcess actionFinanceDataProcess = new ActionFinanceDataProcess();

                actionFinanceDataProcess.init("public/" + fileName, sepDate, days);
                List<Bag> list = actionFinanceDataProcess.readXLS();
                if (list != null) {
                    List<Bag> rst = actionFinanceDataProcess.search(list);
                    actionFinanceDataProcess.generateResult(rst);
                }
            }
            System.out.println("Processed Finished");
        } else {
            System.out.println("Processing the data with default date:xxxx-10-01 and the days before/after is 3" +'\n'+
                    "Please enter the sepDate(xxxx-xx-xx) " +'\n'+
                    "and days number that after/before the sepDate" +'\n'+
                    "if you want.");
            File file = new File("public/");
            File[] files = file.listFiles();
            for (File subFile : files) {
                String fileName = subFile.getName();
                ActionFinanceDataProcess actionFinanceDataProcess = new ActionFinanceDataProcess();

                actionFinanceDataProcess.init("public/" + fileName, "2000-10-01", 3);
                List<Bag> list = actionFinanceDataProcess.readXLS();
                if (list != null) {
                    List<Bag> rst = actionFinanceDataProcess.search(list);
                    actionFinanceDataProcess.generateResult(rst);
                }
            }
            System.out.println("Processed Finished");
        }
    }
}
